package it.myAndroid.ShadowSMS;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;
import android.util.Log;


/**
 * @author stefazzi
 * @date 19/feb/2013
 * @version 
 */
@SuppressWarnings("unused")
public class ShadowSMSDBHelper 
{

  private static final String DB_PATH = "/data/data/it.myAndroid.Encryptiko/databases/";
  private static final String DATABASE_NAME = "encryptiko.db"; 
  public static final  String TABLE_SMS = "SMS"; 
  public static final  String TABLE_BLACKLIST = "BLACKLIST";
  public static final  String KEY_ID = "_id";
	public static final  String KEY_NUMBER = "number";
	public static final  String KEY_BODY = "body";
	public static final  String KEY_STATUS = "status";
  public static final  String KEY_BLID = "_id";
	public static final  String KEY_BLNUMBER = "number";
	public static final  String KEY_BLNAME = "name";

	private static final int DATABASE_VERSION = 1; 
	
  private SQLiteDatabase db; 
  private EncryptikoDB encrypticoDB;
  private final Context	context;
  
  public ShadowSMSDBHelper(Context ctx) throws ShadowSMSDBException 
  {
    try
    {
    	this.context = ctx;
    	encrypticoDB = new EncryptikoDB(context);
    	Thread.setDefaultUncaughtExceptionHandler(new ShadowSMSExceptionHandler(ctx));
    }
    catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
  }

	public ShadowSMSDBHelper open() throws ShadowSMSDBException 
	{
		try
		{
			db = encrypticoDB.getWritableDatabase();
			return this;
		}
		catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}
	
	public void close() throws ShadowSMSDBException 
	{
		try
		{
			encrypticoDB.close();
		}
		catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}
	 	
	// Aggiunge un nuovo SMS 
	public long addContact(ShadowSMSSms shadowSMSSms) throws ShadowSMSDBException
	{ 
		try
		{
		ContentValues values = new ContentValues(); 
	  values.put(KEY_NUMBER, shadowSMSSms.getSmsNumber()); 		// Numero SMS 
	  values.put(KEY_BODY, shadowSMSSms.getSmsBody()); 				// Testo SMS 
	  values.put(KEY_STATUS, shadowSMSSms.getSmsStatus());		// Stato messaggio 0 non letto 1 letto 
	  
	  // Inserisco il record 
	  return db.insert(TABLE_SMS, null, values);
		}
		catch(Exception e)
		{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
		}
	} 
	
  // Legge un singolo SMS dal DB 
	public ShadowSMSSms getSms(int id) throws ShadowSMSDBException
	{ 
		try
		{
	  Cursor cursor = db.query(TABLE_SMS, new String[] { KEY_ID, KEY_NUMBER, KEY_BODY, KEY_STATUS }, KEY_ID + "=?", 
	                               new String[] { String.valueOf(id) }, null, null, null, null); 
	  if (cursor != null)
	    cursor.moveToFirst(); 
	
	    ShadowSMSSms shadowSMSSms = new ShadowSMSSms(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3))); 
	       
	    return shadowSMSSms;
		}
    catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}

	// Legge un singolo SMS dal db e ritorna il cursor
	public Cursor fetchSmsForNumber(int id) throws ShadowSMSDBException
	{
		try
		{
		 Cursor cursor = db.query(TABLE_SMS, new String[] { KEY_ID, KEY_NUMBER, KEY_BODY, KEY_STATUS }, KEY_ID + "=?", 
	                            new String[] { String.valueOf(id) }, null, null, null, null); 
	 	 return cursor;
		}
    catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}
	  
	// Ritorna un cursor con con tutti gli SMS dal db
	public Cursor fetchAllSms() throws ShadowSMSDBException
	{
		try
		{
	  String selectQuery = "SELECT * FROM " + TABLE_SMS + " ORDER BY " + KEY_NUMBER; 
	
	  Cursor cursor = db.rawQuery(selectQuery, null); 
    return cursor;
		}
    catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}
	  
	// Ritorna una lista con tutti gli SMS dal db
	public ArrayList<ShadowSMSSms> getAllSms() throws ShadowSMSDBException
	{ 
		try
		{
		ArrayList<ShadowSMSSms> smsList = new ArrayList<ShadowSMSSms>(); 
    String selectQuery = "SELECT * FROM " + TABLE_SMS + " ORDER BY " + KEY_NUMBER; 
	
    Cursor cursor = db.rawQuery(selectQuery, null); 
	
	  // loop per le righe del DB 
	  if (cursor.moveToFirst()) 
	  { 
	    do 
	    { 
	      ShadowSMSSms shadowSMSSms = new ShadowSMSSms(); 
	      shadowSMSSms.setId(Integer.parseInt(cursor.getString(0))); 
	      shadowSMSSms.setSmsNumber(cursor.getString(1)); 
	      shadowSMSSms.setSmsBody(cursor.getString(2)); 
	      shadowSMSSms.setSmsStatus(Integer.parseInt(cursor.getString(3)));
	    
	      // Aggiungo il record  
	      smsList.add(shadowSMSSms); 
      } while (cursor.moveToNext()); 
     } 
      return smsList;
		}
    catch(Exception e)
    {
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
    }
 } 
	
	// Aggiorna un singolo SMS 
	public boolean updateSms(ShadowSMSSms shadowSMSSms) throws ShadowSMSDBException
	{ 
	  try
	  {
    ContentValues values = new ContentValues(); 
	  values.put(KEY_NUMBER, shadowSMSSms.getSmsNumber()); 
	  values.put(KEY_BODY, shadowSMSSms.getSmsBody()); 
	  values.put(KEY_STATUS, shadowSMSSms.getSmsStatus());
	
	  return db.update(TABLE_SMS, values, KEY_ID + " = ?", new String[] { String.valueOf(shadowSMSSms.getId()) }) > 0;
	  }
    catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	} 
	
	// Cancella un singolo SMS 
	public boolean deleteSms(ShadowSMSSms shadowSMSSms) throws ShadowSMSDBException
	{ 
		try
		{
	  return db.delete(TABLE_SMS, KEY_ID + " = ?", new String[] { String.valueOf(shadowSMSSms.getId()) }) > 0;
		}
    catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}  
	  
	// Cancella tutti gli SMS archiviati
	public boolean deleteAllSms() throws ShadowSMSDBException
	{
		try
		{
	  return db.delete(TABLE_SMS, null, null) > 0;
		}    
		catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
	}
	
	// Ritorna il numero di SMS 
	public int getContactsCount() throws ShadowSMSDBException
	{ 
		try
		{
	  String countQuery = "SELECT  * FROM " + TABLE_SMS; 
	  Cursor cursor = db.rawQuery(countQuery, null); 
	  cursor.close(); 
	
    return cursor.getCount();
		}    
		catch(Exception e)
  	{
    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
    	throw new ShadowSMSDBException("Errore classe DBHelper");
  	}
   }
	  
 	public class EncryptikoDB extends SQLiteOpenHelper
	{
	  
	  public EncryptikoDB(Context context)
		{
	  	super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db)
		{
			try
			{
			// Creo la tabella contenente SMS
		  String CREATE_SMS_TABLE = "CREATE TABLE " + TABLE_SMS + "("
		         + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NUMBER + " TEXT,"
		         + KEY_BODY + " TEXT," + KEY_STATUS + " INTEGER" + ")"; 
		  // Creo la tabella contenente blacklist
    	String CREATE_BLACKLIST_TABLE = "CREATE TABLE " + TABLE_BLACKLIST + "("
		         + KEY_BLID + " INTEGER PRIMARY KEY," + KEY_BLNUMBER + " TEXT,"
		         + KEY_BLNAME + " TEXT" + ")"; 

	  	db.execSQL(CREATE_SMS_TABLE);
		 	db.execSQL(CREATE_BLACKLIST_TABLE); 
			}
	    catch(Exception e)
	  	{
	    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
	  	}
	 	}
		
	 	@Override
	 	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	 	{
	 		try
	 		{
	    // Cancello la vecchia tabella 
	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SMS); 
	
	    // Ricreo la tabella con la nuova versione
	    onCreate(db);
		    
	    // Cancello la vecchia tabella 
	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLACKLIST); 
  
	    // Ricreo la tabella con la nuova versione
		  onCreate(db);
	 		}    
	 		catch(Exception e)
	  	{
	    	Log.e(ShadowSMSDBHelper.class.getName(),"Error",e);
	  	}

		}
	}
}
